package hapinvion.android.lib;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.talk.phonedetectlib.PhoneDetectListener;
import com.talk.phonedetectlib.PhoneDetectSDK;
import com.talk.phonedetectlib.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class WelcomeActivity extends Activity {

    private WebView webView;

    private Handler handler;
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                switch (msg.what) {
                    case 0:
                        Toast.makeText(WelcomeActivity.this, "上传失败.", Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Toast.makeText(WelcomeActivity.this, "上传成功.", Toast.LENGTH_LONG).show();
                        break;

                }
            }
        };

        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        PhoneDetectSDK.getInstance().setAppKey("uL63NkSa6x6n67Ytv7fts60IxJ4nf7KE");
        //检测电池
//        PhoneDetectSDK.getInstance().startBatteryDetect(MainActivity.this);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    URI uri = URI.create(url);
                    if ("native".equalsIgnoreCase(uri.getScheme()) && "startdetect".equalsIgnoreCase(uri.getHost())) {
                        //show detect activity
                        PhoneDetectSDK.getInstance().startHardwareDetect(WelcomeActivity.this, new PhoneDetectListener() {
                            @Override
                            public void onResult(int code, final String value) {
                                Log.e("test", value);
                                if (value != null && !"{}".equalsIgnoreCase(value.trim())) {
                                    dialog = ProgressDialog.show(WelcomeActivity.this, "", "上传数据中...", true, true);
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            doWork(value);
                                        }
                                    }).start();
//                                new UploadResultAsyncTask().execute(value);
                                }
                            }
                        });
                        return true;
                    }
                } catch (Exception e) {
                    Log.e("WelcomeActivity", "error", e);
                }
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("WelcomeActivity", "onPageFinished: " + url);
                webView.loadUrl("javascript:setInAppWebview()");

                String imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
                String brandName = Build.BRAND;
                String modelName = Build.MODEL;
                String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                String jsFormat = "javascript:XS.getDeviceInfo('%s', '%s', '%s')";
                String jsinvoke = String.format(jsFormat, brandName + " " + modelName, imei, androidId);
                Log.i("WelcomeActivity", jsinvoke);
                webView.loadUrl(jsinvoke);
            }
        });



        webView.loadUrl("http://115.28.210.6:8000/");

        Calendar instance = Calendar.getInstance();
        Calendar expireDate = new GregorianCalendar(2015, GregorianCalendar.MAY, 23);
        if (instance.getTimeInMillis() > expireDate.getTimeInMillis()) {
            Toast.makeText(this, "该版本已经过期，5秒后自动退出...", Toast.LENGTH_LONG).show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 5000);
        }
    }


    private void doWork(String param) {
        String brandName = Build.BRAND;
        String modelName = Build.MODEL;
        String cpuModel = getCpuInfo() != null && getCpuInfo().length > 0 ? getCpuInfo()[0] : "";
        String memory = getTotalRAM();
        String deviceno = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
        StringBuilder faultCodes = new StringBuilder();
        try {
            JSONObject jsonObject = new JSONObject(param);
            JSONArray assistDetect = jsonObject.getJSONArray("AssistDetect");
            for (int i = 0; i < assistDetect.length(); i++) {
                JSONObject jsonObject1 = assistDetect.getJSONObject(i);
                int hwType = jsonObject1.getInt("hwType");
                int healthValue = jsonObject1.getInt("healthValue");
                String code = "";
                switch (hwType) {
                    case 3: //GPS
                        code = "001";
                        break;
                    case 2: //WIFI
                        code = "002";
                        break;
                    case 7: //扬声器
                        code = "003";
                        break;
                    case 9: //震动器
                        code = "004";
                        break;
                    case 11: //麦克风
                        code = "005";
                        break;
                    case 16: //螺旋仪
                        code = "006";
                        break;
                    case 20: //指南针
                        code = "007";
                        break;
                    case 13: //加速传感器
                        code = "008";
                        break;
                    case 5:  //前置摄像头
                        code = "009";
                        break;
                    case 4: //后置摄像头
                        code = "010";
                        break;
                }
                if (healthValue != 0 && !TextUtils.isEmpty(code)) {
                    faultCodes.append(code).append(",");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

//            String postBody = "op=submitexaminingreport&userid=&"
        StringBuilder postbody = new StringBuilder("op=submitexaminingreport&userid=&access_token=");
        try {
            postbody.append("&").append("brandname=").append(URLEncoder.encode(brandName, "UTF-8"));
            postbody.append("&").append("modelname=").append(URLEncoder.encode(modelName, "UTF-8"));
            postbody.append("&").append("CPUmodel=").append(URLEncoder.encode(cpuModel, "UTF-8"));
            postbody.append("&").append("memory=").append(URLEncoder.encode(memory, "UTF-8"));
            postbody.append("&").append("deviceno=").append(URLEncoder.encode(deviceno, "UTF-8"));
            postbody.append("&").append("faultcodes=").append(URLEncoder.encode(faultCodes.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            String response = HttpURLConnection_Post(postbody.toString());
            Log.i("WelcomeActivity", "post data: " + postbody.toString());
            Log.i("WelcomeActivity", "response: " + response);
            if (!TextUtils.isEmpty(response)) {
                JSONObject jsonObject = new JSONObject(response);
                if ("success".equalsIgnoreCase(jsonObject.getString("status"))) {
                    handler.sendEmptyMessage(1);
                    Log.i("WelcomeActivity", "upload success");
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handler.sendEmptyMessage(0);
        Log.i("WelcomeActivity", "upload failed");
    }

    public String HttpURLConnection_Post(String postBody) throws IOException {
        //通过openConnection 连接
//        URL url = new java.net.URL("http://101.227.244.200:99");
        HttpURLConnection urlConn = null;
        try {
            URL url = new URL("http://101.227.244.200:99");
            urlConn = (HttpURLConnection) url.openConnection();
            //设置输入和输出流
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setConnectTimeout(15000);
            urlConn.setReadTimeout(15000);

            urlConn.setRequestMethod("POST");
            urlConn.setUseCaches(false);
            // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
            // 要注意的是connection.getOutputStream会隐含的进行connect。
            urlConn.connect();
            //DataOutputStream流
            DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
            //要上传的参数
            //将要上传的内容写入流中
            out.writeBytes(postBody);
            //刷新、关闭
            out.flush();
            out.close();

            //Get Response
            InputStream is = urlConn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConn != null) {
                urlConn.disconnect();
            }
        }
        return null;
    }

    public String[] getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""};
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (IOException e) {
            Log.e("WelcomeActivity", "error get cpu info.", e);
        }
        return cpuInfo;
    }

    public static String getTotalRAM() {
        RandomAccessFile reader = null;
        String load = null;
        try {
            reader = new RandomAccessFile("/proc/meminfo", "r");
            load = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // Streams.close(reader);
        }
        load = load.replace("MemTotal:   ", "");
        return load.trim();
    }
    /*

    private class UploadResultAsyncTask extends AsyncTask<String, Integer, Boolean> {

           private ProgressDialog dialog;


        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(WelcomeActivity.this, "", "上传数据中...", true, true);

        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            dialog.dismiss();
            if (aBoolean) {
                Toast.makeText(WelcomeActivity.this, "上传成功.", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(WelcomeActivity.this, "上传失败.", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected Boolean doInBackground(String... params) {
            return doWork(params[0]);
        }


    }*/

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }
}
